const getNetTable = (array) => {
  if (array && array.length) {
    let netArray = [];
    for (let i = 0, length = array.length; i < length; i = i + 2) {
      let tempArray = [];
      let [x1, y1] = [array[(i + length - 2) % length], array[(i + length - 1) % length]];
      let [xm, ym] = [array[i], array[i + 1]];
      let [x2, y2] = [array[(i + length + 2) % length], array[(i + length + 3) % length]];
      if (y1 > ym) {
        let deltaX = xm === x1 ? 0 : ((x1 - xm) / (y1 - ym));
        let obj = {
          deltaX,
          yMax: y1,
          xMin: xm
        };
        tempArray.push(obj);
      }
      if (y2 > ym) {
        let deltaX = xm === x2 ? 0 : ((x2 - xm) / (y2 - ym));
        let obj = {
          deltaX,
          yMax: y2,
          xMin: xm
        };
        tempArray.push(obj);
      }
      if (netArray[ym]) {
        netArray[ym] = netArray[ym].concat(tempArray);
      } else {
        netArray[ym] = tempArray;
      }
    }
    return netArray;
  }
}

const getAETable = (netTable) => {
  if (!netTable) return;
  let yMin = 0;
  let aeTable = [];
  for (let i = 0, length = netTable.length; i < length; i++) {
    aeTable[i] = [];
    if (netTable[i]) {
      let netArray = netTable[i];
      netArray.forEach(obj => {
        if (obj['yMax'] > i) {
          aeTable[i].push({
            deltaX: obj['deltaX'],
            yMax: obj['yMax'],
            x: obj['xMin']
          });
        }
      });
    }
    if (i > 0) {
      aeTable[i - 1].forEach(obj => {
        if (obj['yMax'] > i) {
          aeTable[i].push({
            deltaX: obj['deltaX'],
            yMax: obj['yMax'],
            x: obj['x'] + obj['deltaX']
          });
        }
      })
    }
  }
  return aeTable;
}

let data =[6, 1, 1, 2, 1, 8, 5, 6, 10, 9, 10, 4];
//  [7, 1, 2, 3, 2, 9, 7, 7, 13, 10, 13, 5]
let [canvasWeight, canvasHeight] = [document.getElementById('webgl').offsetWidth, document.getElementById('webgl').offsetHeight];

let onePXInWebglLength = 2 / canvasHeight;

let [webglToPxX, webglToPxY] = [canvasWeight / 2, canvasHeight / 2];
// let [webglToPxX, webglToPxY] = [1, 1];

let [xMin, yMin] = [data[0], data[1]];

// let newDataForPX = [];
// for (let i = 0, length = data.length; i < length; i += 2) {
//   let [x, y] = [data[i] * webglToPxX, data[i] * webglToPxY];
//   newDataForPX.push(x, y);
//   xMin = xMin > x ? x : xMin;
//   yMin = yMin > y ? y : yMin;
// }

// let [offsetX, offsetY] = [xMin < 0 ? -xMin : 0, yMin < 0 ? -yMin : 0];

// for (let i = 0, length = data.length; i < length; i += 2) {
//   data[i] = Math.round(offsetX + data[i]);
//   data[i + 1] = Math.round(offsetY + data[i + 1]);
// }

// let netTable = getNetTable(data);
console.log(getAETable(getNetTable(data)));